# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import requests
from pyquery import PyQuery as pq
from common.models import Api, ApiArgs, ApiResponses, ApiResponsesCodes, Product
import re


def init():
    req = requests.get('http://doc.hfjy.red/')
    html = req.text
    doc = pq(html)
    product = Product()
    product.name = '产品一'
    product.description = '产品一描述'
    product.save()
    for i in doc('button').items():
        con = i.attr('onclick').lstrip('route(').rstrip(');').split(',')
        if con[0] == "'C'":
            url_name = con[1].strip("'")
            api_json = eval(
                requests.get('http://doc.hfjy.red/content.html?type=C&name=' + url_name + '&outType=json').text)
            for ii in api_json['actionList']:
                api_list = Api()
                api_list.product = product
                api_list.name = ii['actionName']
                api_list.description = ii['memo']
                api_list.uri = \
                re.findall(r"https://xue-dev.hfjy.com(.+?)" + ii['actionName'], ii['call_sample'].replace('\\', ''))[0]
                api_list.save()
                if ii['parms']:
                    for p in ii['parms']:
                        api_args = ApiArgs()
                        api_args.api = api_list
                        api_args.args_name = p["name"]
                        api_args.args_data_type = p['type']
                        api_args.check_type = p['checkType']
                        api_args.check_value = p['checkValue']
                        api_args.description = p['memo']
                        api_args.save()
                if ii['returns']:
                    for rt in ii['returns']:
                        api_responses = ApiResponses()
                        api_responses.api = api_list
                        api_responses.field = rt['name']
                        api_responses.type = rt['type']
                        api_responses.description = rt['memo']
                        api_responses.save()
                if ii['codes']:
                    for c in ii['codes']:
                        api_responses_codes = ApiResponsesCodes()
                        api_responses_codes.api = api_list
                        api_responses_codes.code = c['code']
                        api_responses_codes.description = c['memo']
                        api_responses_codes.save()


